package com.ymx.darling.transaction.jdbc;

import com.ymx.darling.datasource.defaults.PooledDataSource;
import com.ymx.darling.transaction.TransactionManager;

import javax.sql.DataSource;

/**
 * 事务工厂实例
 * 负责创建事务
 *
 * @author 爱java的小于
 */
public class JdbcTransactionManager implements TransactionManager {
    /**数据源*/
    private final DataSource dataSource;

    public JdbcTransactionManager(DataSource dataSource){
        this.dataSource = dataSource;
        //钩子函数 确保应用程序关闭时释放池中所有连接
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (this.dataSource instanceof PooledDataSource) {
                ((PooledDataSource)this.dataSource).forceCloseAll();
            }
        }));
    }

    /**
     * 返回数据源
     * @return DataSource
     */
    public DataSource getDataSource(){
        return this.dataSource;
    }

    /**
     * 创建事务
     * @param isAutoCommit 事务是否自动提交
     * @return Transaction实例
     */
    public JdbcTransaction createTransaction(boolean isAutoCommit){
        return new JdbcTransaction(this.dataSource, isAutoCommit);
    }
}